package com.controller;

import com.entity.Book;
import com.entity.Category;
import com.entity.User;
import com.service.IBookService;
import com.service.IUserService;
import com.util.MD5Util;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Author: foshou.zhang
 * Date : 2016/3/5 0005
 * Time :下午 3:15
 */
@RequestMapping("login")
@Controller
public class LoginController {
    @Resource
    private IUserService userService;
    @Resource
    private IBookService bookService;

    //转到登陆页面
    @RequestMapping("/toLogin")
    public String toLogin() {
        System.out.println("to login page");
        return "login";
    }

    //登陆,进入主页面
    @RequestMapping("/logining")
    public String login(User user, HttpServletRequest request, ModelMap modelMap) {
        if (userService.login(user)) {
            request.getSession().setAttribute("loginUser", user.getUsername());
            System.out.println("username = " + user.getUsername());
//            modelMap.addAllAttributes("category",bookService.listCategory());
            List list = bookService.listCategory();
            //得到ID最小的父分类名称，子分类名称
            Map map = bookService.getMinCategory();
            //根据父分类查询所有该父分类的子分类
            List<Category> subCategoryNames = bookService.getSubCategory(map.get("category_name").toString());
            System.out.println("subCategoryNames = " + subCategoryNames);
            //根据子分类查询书籍的相关信息
            List<Book> books = bookService.getBookInfoBySubCategoryName(map.get("sub_category_name").toString());
            System.out.println("books = " + books);
            System.out.println("list = " + list);
            modelMap.addAttribute("category", list);
            modelMap.addAttribute("subCategory", subCategoryNames);
            return "main";
        } else {
            request.getSession().setAttribute("loginError", "用户名或密码错误！");
            System.out.println(" login  user = " + user);
            return "redirect:toLogin.html";
        }
    }

    /**
     * @param request
     */
    public void getSubCategory(HttpServletRequest request) {

    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping("logout")
    public String logout() {
        return "login";
    }
}
